import React, { useState, useEffect } from 'react';
import { Card, Button } from 'antd';
import { TextArea, TextBox } from 'devextreme-react';
import { model, schema } from '@/ts/base';
import { getUuid } from '@/utils/tools';
import FullScreenModal from '@/components/Common/fullScreen';
import { FieldSelect } from '@/components/Common/FlowDesign/Config/Rule/modal/FieldSelect';

/**
 * 赋值规则
 */

interface Iprops {
  primarys: schema.XForm[];
  details: schema.XForm[];
  current: model.NodeAssignmentRule;
  onOk: (rule: model.NodeAssignmentRule) => void;
  onCancel: () => void;
}

type ValueType = {
  primary: any;
  detail: any;
};

const Assignment: React.FC<Iprops> = ({ primarys, details, current, onCancel, onOk }) => {
  const initMap = new Map([
    [
      getUuid(),
      {
        primary: {},
        detail: {},
      },
    ],
  ]);
  const [targetSource, setTargetSource] = useState<model.MappingData[]>([]);
  const [targetDetailSource, setTargetDetailSource] = useState<model.MappingData[]>([]);
  const [dataMap, setDataMap] = useState<Map<string, ValueType> | undefined>();
  const [assignName, setAssignName] = useState<string>('');
  const [assignRemark, setAssignRemark] = useState<string>('');

  useEffect(() => {
    if (current?.assignments) {
      const newDataMap = new Map();
      current.assignments.forEach((item) => {
        newDataMap.set(getUuid(), item);
      });
      setDataMap(newDataMap);
      setAssignName(current.name);
      setAssignRemark(current.remark);
    } else {
      setDataMap(initMap);
    }
  }, [current]);

  useEffect(() => {
    const tgs: model.MappingData[] = [];
    const detailTgs: model.MappingData[] = [];
    primarys.forEach((a, index) => {
      tgs.unshift(
        ...a.attributes.map((s) => {
          return {
            id: s.id,
            key: index.toString() + s.id,
            formId: a.id,
            formName: a.name,
            typeName: '属性',
            trigger: s.id,
            code: s.code,
            name: s.name,
            widget: s.widget,
            valueType: s.valueType,
          };
        }),
      );
    });
    details.forEach((a, index) => {
      const { id, name, attributes } = a;
      const commonFields = {
        formId: id,
        formName: name,
        typeName: '属性',
      };
      detailTgs.push({
        ...commonFields,
        id: 'belongId',
        key: `belongId`,
        trigger: 'belongId',
        code: 'BELONG_ID',
        name: '归属',
        valueType: '用户型',
      });

      const attributeDetails = attributes.map((s) => ({
        ...commonFields,
        id: s.id,
        key: `${index}${s.id}`,
        trigger: s.id,
        code: s.code,
        name: s.name,
        widget: s.widget,
        valueType: s.valueType,
      }));

      detailTgs.unshift(...attributeDetails);
    });
    setTargetSource(tgs);
    setTargetDetailSource(detailTgs);
  }, [primarys, details]);

  const conditionChange = () => {
    if (dataMap) {
      return Array.from(dataMap.values());
    } else {
      return Array.from(initMap.values());
    }
  };

  const renderElement = () => {
    return (
      <div
        style={{
          height: '300px',
          overflowY: 'scroll',
        }}>
        {dataMap &&
          Array.from(dataMap).map(([key, _value], index) => {
            const primaryValueType = dataMap.get(key)?.primary?.valueType;
            const primaryWidget = dataMap.get(key)?.primary?.widget;
            const detailTargets = targetDetailSource.filter(
              (f) => f.valueType === primaryValueType || f.widget === primaryWidget,
            );
            return (
              <div
                key={key}
                style={{
                  marginBottom: '10px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  flexWrap: 'wrap',
                }}>
                <div>{index + 1}</div>
                <div>
                  <FieldSelect
                    style={{ flex: 'auto' }}
                    value={dataMap.get(key)?.primary}
                    buttonText="主表选择"
                    onChange={(e: model.MappingData) => {
                      const newValue = {
                        detail: {},
                        primary: e,
                      };
                      const newDataMap = new Map(dataMap);
                      newDataMap.set(key, newValue);
                      setDataMap(newDataMap);
                    }}
                    data={targetSource}
                  />
                </div>
                <div>
                  <FieldSelect
                    style={{ flex: 'auto' }}
                    value={dataMap.get(key)?.detail}
                    buttonText="子表选择"
                    onChange={(e: model.MappingData) => {
                      const newValue = {
                        detail: e,
                        primary: dataMap.get(key)!.primary,
                      };
                      const newDataMap = new Map(dataMap);
                      newDataMap.set(key, newValue);
                      setDataMap(newDataMap);
                    }}
                    data={detailTargets}
                  />
                </div>
                <div>
                  <Button
                    type="link"
                    onClick={() => {
                      if (dataMap) {
                        const newMap = new Map(dataMap);
                        newMap.delete(key);
                        setDataMap(newMap);
                      }
                    }}>
                    删除
                  </Button>
                </div>
              </div>
            );
          })}
      </div>
    );
  };

  return (
    <FullScreenModal
      open={true}
      title={'赋值规则'}
      destroyOnClose
      width={'60vw'}
      bodyHeight={'65vh'}
      onSave={() => {
        onOk.apply(this, [
          {
            id: current?.id ?? getUuid(),
            type: 'assignment',
            name: assignName,
            remark: assignRemark,
            assignments: conditionChange(),
            trigger: [],
          },
        ]);
      }}
      onCancel={onCancel}>
      <div>
        <TextBox
          label="名称"
          labelMode="floating"
          value={assignName}
          onValueChange={(e) => {
            setAssignName(e);
          }}
        />
        <Card
          title="子表赋值规则"
          extra={
            <Button
              type="link"
              onClick={() => {
                const newMap = new Map(dataMap || initMap);
                newMap.set(getUuid(), {
                  primary: {},
                  detail: {},
                });
                setDataMap(newMap);
              }}>
              新增一条
            </Button>
          }>
          {renderElement()}
        </Card>
        <TextArea
          label="备注"
          labelMode="floating"
          onValueChanged={(e) => {
            setAssignRemark(e.value);
          }}
          value={assignRemark}
        />
      </div>
    </FullScreenModal>
  );
};
export default Assignment;
